﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Resources;
using ClassLibrary;
using System.Diagnostics;
using Param = ClassLibrary.Parameters.Values;
using ControlLibrary;
using System.Security.Permissions;

namespace MyGoogleMap
{
    /****** NORMES *************
     *     //Couleur Icones
     *     //Sous Gimp : Colorier 205 - 92 - 0
     *     
     * //Popup :
     * ForBorderStyle : FixedToolWindow
     * Locked = true;
     * Maximize/Minimize box = false;
     * ShowInTaskBar = false;
     * StartPos = centerParent
     */

    //***** FONCTIONNALITES ****

    //Dans panel_Marker_onModifiedClick
    // mettre le mru à false;

    //Regarder pour faire des url relatives
    //A chaque enregstrement, créer le fichier dataset qui va bien
    //Clique sur publier : 
    //form avec une progress bar, et un message :
    // transfert vers le serveur en cours (1/4) nom du fichier
    //Si erreur : une erreur est survenue lors du transfert, dire quel fichier
    // si possible, puis demander de checker les paramètres. 

    //Si on n'a pas associé d'icon à un marquerur ça pose problème aussi
    /*    function UrlExists(url)
    {
        var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        return http.status!=404;
    }*/

    //Ajouter un système de regroupement (pour les voyages par exemple)

    //Réflechir sur la possibilité d'importer les icones google map

    //Création de tracés

    //En fait on vire le système de connexion automation et d'import, ça fou la merde
    //Par contre, lors de la publication, ça serait bien de sauver le fichier de données, la carte
    //et de proposer l'import sur internet si les paramètres sont ok

    //Menu Afficher dossier et blablabla

    //Réflexion sur la synchro. 

    //Bug de la sauvegarde du splitter

    //ConfigParameters, il faut tester la creation de dossiers en mode config
    //if (_modeConfig == true)


    //Un quick puhlish pour envoyer le JS et nes nouvelles images si besoin et un full
    //pour faire un zip complet du projet


    //***** UI ****
    //Faire en sorte que l'ascenseur des catégories et des event ne s'affiche que quand le curseur
    //passe dessus

    //***** CODE ****
    //Faire une grosse revue de code
    //Véfifier que parmis les composants il n'y ai pas de ingerop (genre list box add sup)
    //Essayer d'homogeneiser les noms d'evenement des controls ainsi que leur description
    //Trouver un truc plus propre pour que les paramètres par défaut ne soient pas dans parameters

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]

    public partial class MainForm : Form
    {
        private bool _fileModified;
        private bool FileModified
        {
            get { return _fileModified; }
            set
            {
                _fileModified = value;
                this.Text = _caption;
                if (_fileModified)
                    toolStripMenuItem_Save.Enabled = true;
                else toolStripMenuItem_Save.Enabled = false;
            }
        }
        private string _caption
        {
            get
            {
                string name = Application.ProductName;

                if (null != Param.localPath_UserFile)
                {
                    if (Param.localPath_UserFileName == string.Empty)
                    {
                        return name;
                    }
                    else
                    {
                        if (FileModified)
                        {
                            return name + " - " + Param.localPath_UserFileName + "*";
                        }
                        return name + " - " + Param.localPath_UserFileName;
                    }
                }
                else return this.Text;
            }
        }
        bool _init;

        //List<Marker> _markerList;
        Marker _currentMarker;
        //List<string> _categories;

        #region INIT
        
        public MainForm()
        {
            _init = true;
            if(string.Empty != Properties.Settings.Default.Language)
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.Language);

            InitializeComponent();

            Param.RM = Properties.Resources.ResourceManager;
            Param.MarkerList = new List<Marker>();
            Param.Categories = new List<string>();
            Param.PARAM_LANGUAGE = Thread.CurrentThread.CurrentUICulture.Name;
            _currentMarker = new Marker();
            FileModified = false;

            ErrorManager.errorOccured += new ErrorManager.ErrorOccurred(ErrorManager_errorOccured);

            _init = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //Language_check(Thread.CurrentThread.CurrentUICulture.Name);
            splitContainer1.SplitterDistance = Properties.Settings.Default.SplitterDistance;
            //UpdateUI();

            //Initialisation de la taille et position de la fenêtre principale
            /*this.Width = Properties.Settings.Default.MainForm_Width;
            this.Height = Properties.Settings.Default.MainForm_Height;
            int x = Properties.Settings.Default.MainForm_X > 0 ? Properties.Settings.Default.MainForm_X : 0;
            int y = Properties.Settings.Default.MainForm_Y > 0 ? Properties.Settings.Default.MainForm_Y : 0;

            this.Location = new Point(x, y);

            if (Properties.Settings.Default.WindowsState == 0)
                this.WindowState = FormWindowState.Maximized;
            else this.WindowState = FormWindowState.Normal;

            //Initialisation des splitterDistance
            splitContainer_Main.SplitterDistance = Properties.Settings.Default.SplitterDistance_Main;
            editMarker.spliter_param_distance = Properties.Settings.Default.SplitterDistance_Params;
            editMarker.spliter_param_map_distance = Properties.Settings.Default.SplitterDistance_Params_Map;*/

            bool RC;

            RC = panel_Marker.setGMap();
            if(true == RC) RC = panel_Marker.Init();
        }

        #endregion

        #region ERROR
        void ErrorManager_errorOccured(string msg)
        {
            MessageBox.Show(this, msg, Param.RM.GetString("MB_ErrorCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        #endregion

        //LANGUAGE
        private void UpdateUI()
        {
            ResourceManager _RM = new ResourceManager("MyGoogleMap.MainForm", typeof(MainForm).Assembly);
            try
            {
                #region Files
                toolStripMenuItem_Files.Text = _RM.GetString("toolStripMenuItem_Files.Text");
                toolStripMenuItem_New.Text = _RM.GetString("toolStripMenuItem_New.Text");
                toolStripMenuItem_Open.Text = _RM.GetString("toolStripMenuItem_Open.Text");
                toolStripMenuItem_Import.Text = _RM.GetString("toolStripMenuItem_Import.Text");
                toolStripMenuItem_Publish.Text = _RM.GetString("toolStripMenuItem_Publish.Text");
                toolStripMenuItem_Save.Text = _RM.GetString("toolStripMenuItem_Save.Text");
                toolStripMenuItem_SaveAs.Text = _RM.GetString("toolStripMenuItem_SaveAs.Text");
                toolStripMenuItem_Display.Text = _RM.GetString("toolStripMenuItem_Display.Text");
                toolStripMenuItem_Offline.Text = _RM.GetString("toolStripMenuItem_Offline.Text");
                toolStripMenuItem_Online.Text = _RM.GetString("toolStripMenuItem_Online.Text");
                toolStripMenuItem_Recent.Text = _RM.GetString("toolStripMenuItem_Recent.Text");
                toolStripMenuItem_Quit.Text = _RM.GetString("toolStripMenuItem_Quit.Text");
                //NEW
                saveFileDialog_MGM.Filter = _RM.GetString("saveFileDialog_MGM.Filter");
                openFileDialog_MGM.Filter = _RM.GetString("saveFileDialog_MGM.Filter");
                #endregion

                #region Configuration
                toolStripMenuItem_Configuration.Text = _RM.GetString("toolStripMenuItem_Configuration.Text");
                toolStripMenuItem_Language.Text = _RM.GetString("toolStripMenuItem_Language.Text");
                toolStripMenuItem_French.Text = _RM.GetString("toolStripMenuItem_French.Text");
                toolStripMenuItem_English.Text = _RM.GetString("toolStripMenuItem_English.Text");
                toolStripMenuItem_Parameters.Text = _RM.GetString("toolStripMenuItem_Parameters.Text");
                toolStripMenuItem_Categories.Text = _RM.GetString("toolStripMenuItem_Categories.Text");
                #endregion

                #region ?
                ToolStripMenuItem_LogFile.Text = _RM.GetString("ToolStripMenuItem_LogFile.Text");
                #endregion

                toolStripMenuItem_DeleteMarker.Text = _RM.GetString("toolStripMenuItem_DeleteMarker.Text");

                //Labels
                linkLabel_AddMarker.Text = Param.RM.GetString("Label_AddMarker");

                panel_Marker.UpdateUI();
                
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("MainForm", "UpdateUI", e, Param.RM.GetString("MB_Error_UpdateUI"));
            }
        }

        private void listBoxUpdateDataSource()
        {
            listBox_Marker.DataSource = null;
            listBox_Marker.DataSource = Param.MarkerList;
            listBox_Marker.DisplayMember = "Title";
            listBox_Marker.ValueMember = "Self";
        }

        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            Properties.Settings.Default.SplitterDistance = splitContainer1.SplitterDistance;
            Properties.Settings.Default.Save();
        }

        #region MARKERS

        //ADD
        private void linkLabel_AddMarker_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                _currentMarker = new Marker();

                checkName(true);

                Param.MarkerList.Add(_currentMarker._Clone());
                listBoxUpdateDataSource();
                listBox_Marker.SelectedIndex = listBox_Marker.Items.Count - 1;
                FileModified = true;
                this.Text = _caption;
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainForm", "linkLabel_AddMarker_LinkClicked", ex);
            }
        }

        //CHECK
        private bool checkName(bool newMarker)
        {
            try
            {
                //Check if _currentMarker.title already exists
                bool exist = true;
                string curTitle = _currentMarker.title;

                Marker selectedMarker = (Marker)listBox_Marker.SelectedItem;
                string selectedMarkerTitle = string.Empty;
                if (null != selectedMarker && !newMarker)
                    selectedMarkerTitle = selectedMarker.title;

                int i = 1;
                while (exist)
                {
                    var count = (from Marker m in Param.MarkerList
                                 where m.title == curTitle && m.title != selectedMarkerTitle
                                 select m).Count();
                    if (0 != count)
                    {
                        curTitle = _currentMarker.title + "(" + i + ")";
                        i++;
                    }
                    else
                    {
                        exist = false;
                        _currentMarker.title = curTitle;
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog ("MainForm", "checkName", e);
                return false;
            }
        }

        //DELETE
        private void contextMenuStrip_ListBoxMarker_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            try
            {
                int idx = listBox_Marker.SelectedIndex;
                contextMenuStrip_ListBoxMarker.Hide();

                if (idx != -1)
                {
                    //Compute selected index after deletion
                    int newIdx = -1;
                    if (listBox_Marker.Items.Count > 1)
                    {
                        if (idx < listBox_Marker.Items.Count - 1)
                            newIdx = idx;
                        else if (idx == listBox_Marker.Items.Count - 1)
                            newIdx = idx - 1;
                    }

                    Marker mToDel = (Marker)listBox_Marker.SelectedItem;
                    if (null != mToDel)
                    {
                        string msg = Param.RM.GetString("MB_DeleteMarker") + mToDel.title + " ?"; 
                        if (MessageBox.Show(this, msg,"", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {
                            Param.MarkerList.Remove(mToDel);
                            _currentMarker = null;
                            listBoxUpdateDataSource();

                            listBox_Marker.SelectedIndex = newIdx;
                        }
                    }
                    else throw new Exception("(Marker)listBox_Marker.SelectedItem is null");
                }

                FileModified = true;
                this.Text = _caption;
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainFram", "contextMenuStrip1_ItemClicked", ex);
            }
        }

        //SELECT
        private void listBox_Marker_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_init)
            {
                try
                {
                    //A marker is selected (work on a copy)
                    if (-1 < listBox_Marker.SelectedIndex)
                    {
                        Marker tmp = listBox_Marker.SelectedItem as Marker;
                        if (null != tmp)
                        {
                            _currentMarker = tmp._Clone();

                            panel_Marker.Init(_currentMarker);
                        }
                        else throw new Exception("Marker tmp is null");
                    }
                    else panel_Marker.Init();
                }
                catch (Exception ex)
                {
                    ErrorManager.WriteLog("MainForm", "listBox_Marker_SelectedIndexChanged", ex);
                }
            }
        }

        //CANCEL
        private void panel_Marker_onCancelClick()
        {
            try
            {
                listBox_Marker.Enabled = true;
                linkLabel_AddMarker.Enabled = true;
                listBox_Marker_SelectedIndexChanged(null, null);
                enableMenu(true);
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("MainFram", "editMarker1_onCancelClick", e);
            }
        }

        //CATEGORY
        private void panel_Marker_onConfigCategoriesClick()
        {
            Form_Parameters param_form = new Form_Parameters(1);
            if (param_form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                panel_Marker.SetListCategorie(Param.Categories);
                FileModified = true;
            }
        }

        private void panel_Marker_onModifiedClick()
        {
            //FileModified = true;
            //this.Text = _caption;
            listBox_Marker.Enabled = false;
            linkLabel_AddMarker.Enabled = false;


            enableMenu(false);

        }

        private void enableMenu(bool enable)
        {
            toolStripMenuItem_Save.Enabled = enable;
            toolStripMenuItem_Recent.Enabled = enable;
            toolStripMenuItem_Publish.Enabled = enable;
            toolStripMenuItem_Open.Enabled = enable;
            toolStripMenuItem_Import.Enabled = enable;
            toolStripMenuItem_New.Enabled = enable;
        }

        //SAVE
        private void panel_Marker_onSaveClick()
        {
            try
            {
                FileModified = true;
                this.Text = _caption;

                listBox_Marker.Enabled = true;
                linkLabel_AddMarker.Enabled = true;

                //Get the marker from editMarker
                _currentMarker = panel_Marker.Marker._Clone();
                _currentMarker.published = false; //Needs to upload img of this marker in next publication

                checkName(false);

                //Update selection
                int selected = listBox_Marker.SelectedIndex;
                if (-1 < listBox_Marker.SelectedIndex)
                {
                    Param.MarkerList[selected] = _currentMarker;

                    //Update the listbox_marker
                    listBoxUpdateDataSource();
                    listBox_Marker.SelectedIndex = selected;
                    listBox_Marker.ClearSelected();

                    enableMenu(true);
                }
                else throw new Exception("Failed to save " + _currentMarker.title);
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("MainForm", "editMarker1_onSaveClick", e);
            }
        }

        private void listBox_Marker_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    int indexOfItemUnderMouseToDrag;
                    indexOfItemUnderMouseToDrag = listBox_Marker.IndexFromPoint(e.X, e.Y);
                    if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
                    {
                        listBox_Marker.SelectedIndex = indexOfItemUnderMouseToDrag;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.WriteLog("MainFrame", "listBox_Marker_MouseDown", ex, Param.RM.GetString("ListBoxMarker_Error"));
            }
        }


        #endregion
        

        private void linkLabel_AddMarker_MouseEnter(object sender, EventArgs e)
        {
            linkLabel_AddMarker.LinkColor = Param.Color_linkLabel_AddMarker_Hover;
        }

        private void linkLabel_AddMarker_MouseLeave(object sender, EventArgs e)
        {
            linkLabel_AddMarker.LinkColor = Param.Color_linkLabel_AddMarker_Default;
        }


    }
}
